package com.gavindon.android.view.combo

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.bumptech.glide.Glide
import com.gavindon.android.R
import com.gavindon.android.base.BaseActivity
import com.gavindon.android.base.INTENT_COMBO_ID
import com.gavindon.android.base.INTENT_GOODS_TYPE
import com.gavindon.android.base.INTENT_PLAY_POSITION
import com.gavindon.android.entity.LoginStatus
import com.gavindon.android.network.BASE_URL_IMG
import com.gavindon.android.network.DataResult
import com.gavindon.android.view.video.PayResultPlay
import com.gavindon.android.viewmodel.ComboViewModel
import com.gavindon.android.widget.GradientDrawableFrameLayout
import com.gavindon.android.widget.LoadDialog
import com.gavindon.android.widget.PayResultDialog
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.toast
import java.util.*
import kotlin.concurrent.timer

/**
 * description: 购买套餐
 * Created by liNan on  2022-3-2 8:58
 */
class BuyActivity : BaseActivity() {
    override val layoutId = R.layout.activity_buy

    private lateinit var ivQrImg: ImageView
    private lateinit var fmlWx: GradientDrawableFrameLayout
    private lateinit var fmlAli: GradientDrawableFrameLayout
    private lateinit var tvUserInfo: TextView
    private lateinit var tvPrice: TextView
    private lateinit var tvExpiredTime: TextView
    private lateinit var mViewModel: ComboViewModel

    //套餐id、课程id
    private var id: String? = null

    private var timer: Timer? = null
    private var checkPayTimer: Timer? = null
    private var handler: Handler? = null
    private var orderId = ""
    private var aliOrderId = ""

    private val wx_pay = "0"
    private val ali_pay = "1"

    //商品类型0课程1套餐
    private var goodsType: Int? = null
    private var playPosition: Int? = 0

    private val dialog: PayResultDialog by lazy {
        PayResultDialog(this)
    }

    override fun onInit(savedInstanceState: Bundle?) {
        mViewModel = getViewModel()
        ivQrImg = findViewById(R.id.iv_pay_qr)
        fmlWx = findViewById(R.id.fml_wx)
        fmlAli = findViewById(R.id.fml_ali)
        tvPrice = findViewById(R.id.tv_price)
        tvExpiredTime = findViewById(R.id.tv_expired_time)
        tvUserInfo = findViewById(R.id.tv_user_account)
        goodsType = intent.getIntExtra(INTENT_GOODS_TYPE, -1)
        id = intent.getStringExtra(INTENT_COMBO_ID)
        playPosition = intent.getIntExtra(INTENT_PLAY_POSITION, 0)
        tvUserInfo.text = LoginStatus.userInfoResp?.realName
        fmlWx.setOnClickListener {
            pay(wx_pay)
        }
        fmlAli.setOnClickListener {
            payAli(ali_pay)
        }
        pay(wx_pay)
        initHandler()
//        showTipDialog()
    }

    /**
     * 1.获取订单信息
     * 2.使用订单id进行获取支付二维码信息
     */
    private fun pay(payType: String) {
        if (id != null) {
            if (goodsType != -1) {
                mViewModel.getOrderId(goodsType.toString(), id!!, payType)
                    .observe(this@BuyActivity) {
                        if (it is DataResult.Success) {
                            timer?.cancel()
                            checkPayTimer?.cancel()
                            orderId = it.data.orderId
                            tvPrice.text = it.data.amount.toString()
                            tvUserInfo.text = it.data.userName
                            tvExpiredTime.text = it.data.validityEndTime
                            if (it.data.payType == ali_pay.toInt()) {
                                aliOrderId = it.data.orderId
                                fetchAliQr()
                            } else {
                                orderId = it.data.orderId
                                tvPrice.text = it.data.amount.toString()
                                tvUserInfo.text = it.data.userName
                                tvExpiredTime.text = it.data.validityEndTime
                                fetchWxQr()
                            }
                        }
                    }
            }

        }
    }

    private fun payAli(payType: String) {
        if (id != null) {
            if (goodsType != -1) {
                mViewModel.getAliOrderId(goodsType.toString(), id!!, ali_pay)
                    .observe(this@BuyActivity) {
                        if (it is DataResult.Success) {
                            timer?.cancel()
                            checkPayTimer?.cancel()
                            if (it.data.payType == ali_pay.toInt()) {
                                orderId = it.data.orderId
                                tvPrice.text = it.data.amount.toString()
                                tvUserInfo.text = it.data.userName
                                tvExpiredTime.text = it.data.validityEndTime
                                fetchAliQr()
                            }
                        }
                    }
            }

        }
    }


    private fun initHandler() {
        handler = Handler(this.mainLooper) {
            when (it.what) {
                wx_pay.toInt() -> {
                    fetchWxQr()
                }
                ali_pay.toInt() -> {
                    fetchAliQr()
                }
                else -> {
                    queryPay()
                }
            }
            return@Handler true
        }
    }

    /*微信支付*/
    private fun fetchWxQr() {
        mViewModel.getWxPayQr(orderId).observe(this) {
            if (it is DataResult.Success) {
                Glide.with(this).load("$BASE_URL_IMG/${it.data}").into(ivQrImg)
                loopQr(wx_pay.toInt())
            }
        }
    }

    /*支付宝支付*/
    private fun fetchAliQr() {
        mViewModel.getAliPayQr(orderId).observe(this) {
            if (it is DataResult.Success) {
                Glide.with(this).load("$BASE_URL_IMG/${it.data}").into(ivQrImg)
                loopQr(ali_pay.toInt())
            }
        }
    }


    /**
     * 定时刷新支付二维码
     * 定时获取支付结果-
     */
    private fun loopQr(payType: Int) {
        timer?.cancel()
        timer = timer(initialDelay = 2 * 60 * 1000L, period = 2 * 60 * 1000L, action = {
            handler?.run {
                sendMessage(obtainMessage(payType))
            }
        })
        loopCheckIsPay()
    }

    /**
     * 轮循检测是否支付
     */
    private fun loopCheckIsPay() {
        checkPayTimer?.cancel()
        checkPayTimer = timer(period = 1500, action = {
            handler?.run {
                sendMessage(obtainMessage(2))
            }
        })
    }

    /**
     * 防止用户使用一种支付类型，又点另一种类型支付
     * 所以两种都进行遍历（订单id不为空时）
     */
    private fun queryPay() {
        if (orderId.isNotEmpty()) {
            mViewModel.checkIsPay(orderId).observe(this) {
                if (it is DataResult.Success) {
                    if (it.data.payStatus == 1) {
                        showTipDialog()
                        /*     toast("您已经支付")
                             checkPayTimer?.cancel()
                             timer?.cancel()
                             val i = Intent()
                             i.putExtra("orderType", goodsType)
                             i.putExtra("id", id)
                             setResult(RESULT_OK, i)
                             this.finish()*/
                    }
                }
            }
        }
        if (aliOrderId.isNotEmpty()) {
            mViewModel.checkIsPay(aliOrderId).observe(this) {
                if (it is DataResult.Success) {
                    if (it.data.payStatus == 1) {
                        showTipDialog()
                        /*        toast("您已经支付")
                                checkPayTimer?.cancel()
                                timer?.cancel()
                                val i = Intent()
                                i.putExtra("orderType", goodsType)
                                i.putExtra("id", id)
                                setResult(RESULT_OK, i)
                                this.finish()*/
                    }
                }
            }
        }
    }

    //显示提示3s对话框
    private fun showTipDialog() {
        dialog.showloading()
        dialog.setIntervalFinish {
            checkPayTimer?.cancel()
            timer?.cancel()
            dialog.cancel()
//            EventBus.getDefault().postSticky(PayResultPlay(playPosition!!))
            val i = Intent()
            i.putExtra("orderType", goodsType)
            i.putExtra("id", id)
            i.putExtra("playPosition", 1)
            setResult(RESULT_OK, i)
            this.finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
        checkPayTimer?.cancel()
    }
}